Day.js is a JavaScript library that lets us manipulate dates in our apps.
In this article, we’ll look at how to use Day.js to manipulate dates in our JavaScript apps.
Convert a UTC Date-Time to Local Date-Time
To convert a UTC date-time to a locale date-time with Day.js, we can use the local
method available with the utc
plugin.
For instance, we can write:
const dayjs = require("dayjs");
const utc = require("dayjs/plugin/utc");
dayjs.extend(utc);
const a = dayjs.utc();
const result = a.local().format();
console.log(result);
to convert date a
, which is in UTC, to a local date-time.
We import the utc
plugin with:
const utc = require("dayjs/plugin/utc");
We can also call utc
with true
to change the time zone without changing the current time:
const dayjs = require("dayjs");
const utc = require("dayjs/plugin/utc");
dayjs.extend(utc);
const result = dayjs("2020-05-03 22:15:01").utc(true).format();
console.log(result);
UTC Offset
To set the UTC offset of a Day.js date, we can use the utcOffset
method available with the utc
plugin with the offset in minutes as the argument:
const dayjs = require("dayjs");
const utc = require("dayjs/plugin/utc");
dayjs.extend(utc);
const result = dayjs().utcOffset(480);
console.log(result);
We set the date to 8 hours ahead of UTC by calling utcOffset
with 480 minutes.
And we can get the UTC offset of a Day.js date by calling utcOffset
with no arguments:
const dayjs = require("dayjs");
const utc = require("dayjs/plugin/utc");
dayjs.extend(utc);
const result = dayjs().utcOffset();
console.log(result);
Conclusion
Day.js is a JavaScript library that lets us manipulate dates in our apps.